package quicklunch.e1.goodies.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * $Date$
 * 
 * @author nakawaka
 * @since 2006/09/15
 * 
 */
public abstract class FileUtils {

	public static final String URL_PROTOCOL_FILE = "file";

	public static File toFile(URL url) throws FileNotFoundException {

		if (!URL_PROTOCOL_FILE.equals(url.getProtocol())) {
			throw new FileNotFoundException(url.getFile()
					+ " cannot be resolved to absolute file path "
					+ "because it does not reside in the file system");
		}

		String s = url.getFile();

		try {
			s = URLDecoder.decode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {

		}
		return new File(s);
	}

	public static void writeFile(File targetDir, String filename, byte[] bs)
			throws IOException {
		targetDir.mkdirs();
		File targetFile = new File(targetDir.getCanonicalPath() + File.separator + filename);
		OutputStream out = null;
		try {
			targetFile.createNewFile();
			out = new FileOutputStream(targetFile);
			out.write(bs);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}

	}
    
    public static List<String> getStrings(InputStream inputStream) throws IOException{
        
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        List<String> list = new ArrayList<String>();
        String line = null;
        while((line = bufferedReader.readLine()) != null){
            list.add(line);
        }
        
        return list;
    }
    
}
